<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="执行编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="executeCode">
              <a-input v-model="model.executeCode" placeholder="请输入执行编码" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalSource">
              <j-dict-select-tag
                type="list"
                v-model="model.approvalSource"
                dictCode="material_price_approval_flow_type"
                placeholder="请选择审批流程"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="执行日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="executeDate">
              <el-date-picker
                style="width: 100%"
                v-model="model.executeDate"
                type="month"
                value-format="yyyy-MM"
                @change="handleChange"
                placeholder="请选择执行日期">
              </el-date-picker>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="引用执行编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="referenceExcuteCode">
              <JDictSelectTag v-model="model.referenceExcuteCode"
                                   placeholder="请输入引用执行编号"
                                   dictCode="material_price_approval,execute_code,execute_code,status=999"
                                   @change="handleSelectReferenceExcuteCode">
              </JDictSelectTag>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="材料价格审批子表" :key="refKeys[0]" :forceRender="true">
        <a-row :gutter="24" style="margin-bottom: 10px;">
          <a-col :span="24">
            <a-button @click="addMaterial" icon="plus">新增</a-button>
            <a-button type="danger"  icon="delete" @click="onDel">删除</a-button>
          </a-col>
        </a-row>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="materialPriceApprovalDetailTable.loading"
          :columns="materialPriceApprovalDetailTable.columns"
          :dataSource="materialPriceApprovalDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          @edit-closed="onEditClosed"
          />
      </a-tab-pane>
      <material-price-select-material-modal ref="selectModal" @orderOk="selMaterialOk" />
    </a-tabs>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
import {
  getRefPromise,
  VALIDATE_FAILED,
  validateFormModelAndTables
} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import { ajaxGetDictItems } from '@api/api'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'
import SelectMaterialModal from '@views/crm/shipment/modules/SelectMaterialModal.vue'
import MaterialPriceSelectMaterialModal from '@views/business/procurement/modules/MaterialPriceSelectMaterialModal.vue'

  export default {
    name: 'MaterialPriceApprovalForm',
    mixins: [JVxeTableModelMixin],
    components: {
      MaterialPriceSelectMaterialModal,
      SelectMaterialModal,
      JFormContainer,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          executeDate: [
            { required: true, message: '请输入执行日期!'},
          ],
          approvalSource: [
            { required: true, message: '请选择审批流程!'},
          ],
        },
        flag:0,
        refKeys: ['materialPriceApprovalDetail', ],
        tableKeys:['materialPriceApprovalDetail', ],
        activeKey: 'materialPriceApprovalDetail',
        // 材料价格审批子表
        materialPriceApprovalDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
           /* {
              title: '物料编码',
              key: 'materialCode',
              type: JVXETypes.popup,
              popupCode:"procurement_material_price_erp",
              orgFields:"code,name,none_spec,me_unit,au_unit,co_rate,id",
              destFields:"materialCode,materialName,sizeModel,mainUtil,fuUtil,conversionRate,materialId",
              field:"code,name,none_spec,me_unit,au_unit,co_rate",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              param:{ searchCode: 'code', searchOpen: true }
            },*/
            {
              title: '物料编码',
              key: 'materialCode',
              type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled:true
            },
            {
              title: '物料名称',
              key: 'materialName',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled:true
            },
            {
              title: '规格型号',
              key: 'sizeModel',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled:true
            },
            {
              title: '主单位',
              key: 'mainUtil',
               type: JVXETypes.input,
              width:"80px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled:true,
              formatter: ({cellValue}) => {
                const item = this.jiUnit.find(item => item.value == cellValue);
                return item ? item.text : cellValue;
              },

            },
/*            {
              title: '辅单位',
              key: 'fuUtil',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled:true,
              formatter: ({cellValue}) => {
                const item = this.zlUnit.find(item => item.value == cellValue);
                return item ? item.text : cellValue;
              },
            },
            {
              title: '换算率',
              key: 'conversionRate',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled:true
            },*/
            {
              title: '供应商',
              key: 'supplier',
              type: JVXETypes.popup,
              popupCode:"select_supplier",
              field:"supplier_name",
              orgFields:"supplier_name",
              destFields:"supplier",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '出厂含税价格',
              key: 'taxPrice',
              type: JVXETypes.inputNumber,   // 建议用 inputNumber，防止输入非法字符
              width: '120px',
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '出厂不含税价格',
              key: 'noTaxPrice',
               type: JVXETypes.inputNumber,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '运费',
              key: 'shippingPrice',
               type: JVXETypes.inputNumber,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '本月价格',
              key: 'price',
               type: JVXETypes.input,
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        jiUnit: [],
        zlUnit: [],
        isDictLoaded:false,
        url: {
          add: "/procurement/materialPriceApproval/add",
          edit: "/procurement/materialPriceApproval/edit",
          queryById: "/procurement/materialPriceApproval/queryById",
          handleChange:"/procurement/materialPriceApproval/handleChange",
          queryReferenceExcuteCode:"/procurement/materialPriceApproval/queryReferenceExcuteCode",
          materialPriceApprovalDetail: {
            list: '/procurement/materialPriceApproval/queryMaterialPriceApprovalDetailByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      customFormData: {
        type: Object,
        default: () => {
          return {}
        },
        required: false,
      },
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      if (this.customFormData.id != null) {
        console.log("aaaaaaaa",this.customFormData)
        this.model = this.customFormData
        this.editAfter()
      }
      this.loadDictData()
    },
    methods: {
      onEditClosed({ row, column }) {
        // 新值根本不在参数里，要去 row 里取
        const newVal = row[column.key];
        console.log('=== 新值', newVal);   // 这下一定不是 undefined
        if (column.key === 'taxPrice') {
          const tax = Number(newVal) || 0;
          row.noTaxPrice = Number((tax / 1.13).toFixed(2));
          row.price = row.noTaxPrice+(row.shippingPrice || 0)
          this.$refs[this.refKeys[0]].reloadRow(row);
        }
        if (column.key === 'shippingPrice') {
          row.price = (row.noTaxPrice ||0)+(row.shippingPrice || 0)
          this.$refs[this.refKeys[0]].reloadRow(row);
        }
      },
      syncDataSource () {
        const $table = this.$refs[this.refKeys[0]]
        if (!$table) return
        console.log('ref 是否存在', this.$refs[this.refKeys[0]])
        console.log('getRecordset 返回', $table.getRecordset())
      },
      onDel() {
        const $table = this.$refs[this.refKeys[0]]
        const selectedRows = $table.getCheckboxRecords()
        if (!selectedRows.length) {
          this.$message.warning('请先勾选要删除的行')
          return
        }
        console.log("删除",selectedRows)
        $table.remove(selectedRows)
        this.materialPriceApprovalDetailTable.dataSource =
          this.materialPriceApprovalDetailTable.dataSource.filter(
            row => !selectedRows.includes(row)
          )
        this.syncDataSource()
      },
      selMaterialOk(rows) {
        console.log("rowsssss",rows)
        if (rows && rows.length > 0) {
          rows.forEach((item) => {
            const exists = this.materialPriceApprovalDetailTable.dataSource.some(
              (d) => d.materialCode === item.code
            );
            if (!exists) {
              this.materialPriceApprovalDetailTable.dataSource.push({
                materialCode: item.code,
                materialName: item.name,
                sizeModel: item.noneSpec,
                mainUtil: item.meUnit,
                fuUtil: item.auUnit,
                conversionRate: item.coRate
              });
            }
          });
        }
        console.log("结果",this.materialPriceApprovalDetailTable.dataSource)
      },
      addMaterial() {
        console.log("1111111111111111")
        console.log('ref=', this.$refs.selectModal)   // 看是否为 undefined
        this.$nextTick(() => {
          this.$refs.selectModal.add()
        })
      },
      handleChange(){
        getAction(this.url.handleChange,{executeDate:this.model.executeDate}).then((res) => {
          if(res.success){
            this.flag=res.result
            if(this.flag===1){
              this.$message.error("该执行日期已存在")
            }
          } else {
            this.$message.error(res.message)
          }
        })
      },
      handleSelectReferenceExcuteCode(){
        console.log("wc",typeof this.model.referenceExcuteCode)
        getAction(this.url.queryReferenceExcuteCode,
          {
          ExcuteCode:this.model.referenceExcuteCode
        }).then((res)=>{
          if(res.success){
            this.$set(this.materialPriceApprovalDetailTable, 'dataSource', res.result)
          }
          else {
            this.$message.error(res.message)
          }
        })
      },
      handleOk() {
      },
      submitForm() {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormModelAndTables(this.$refs.form,this.model, tables)
        }).then(allValues => {
          /** 一次性验证一对一的所有子表 */
          return this.validateSubForm(allValues)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          console.log("11111111111111111111111111111111111111",formData)
          var materialPriceApprovalDetailids = formData.materialPriceApprovalDetailList.map(item=>item.materialCode)
          var checkids=new Set(materialPriceApprovalDetailids)
          if(this.flag===1){
            return this.$message.error("当执行日期已有数据")
          }
          if(checkids.size!==materialPriceApprovalDetailids.length){
            return this.$message.error("请不要选择同一个物料多次")
          }
          // 发起请求
          return this.request(formData)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      },
      applySubmit(record) {
        console.log("aaaaaaaarecord")
        if (record.dataId && record.dataId.length < 1) {
          this.$message.error('审批时必须传入参数dataId')
          return
        }

        //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
        isFirstInitiator(record.dataId, record).then((res) => {
          if (res.success && res.result) {
            // 只有第一次能自动申请
            return
          } else {
            var params = Object.assign(
              {
                dataId: record.dataId,
              },
              record
            )
            definitionStartByDataId(record.dataId, 'MaterialPriceApprovalService', params)
              .then((res) => {
                if (res.success) {
                  this.$message.success(res.message)
                } else {
                  this.$message.error(res.message)
                }
              })
              .finally()
          }
        })
      },

      loadDictData() {
        console.log("字典准备加载")
        ajaxGetDictItems('ji_unit', null).then((res) => {
          if (res.success) {
            this.jiUnit = res.result
            console.log("字典1加载完成")
            this.isDictLoaded=true
          }
        })
        ajaxGetDictItems('zl_unit',null).then((res)=>{
          if(res.success){
            this.zlUnit = res.result
            console.log("字典2加载完成")
          }
        })
      },
      addBefore(){
        this.materialPriceApprovalDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      async editAfter() {
        this.$nextTick(() => {
        })
          // 加载子表数据
          if (this.model.id) {
            let params = { id: this.model.id }
            while (!this.isDictLoaded) {
              await new Promise(resolve => setTimeout(resolve, 100));
              console.log("子表数据加载中...")
            }
            this.requestSubTableData(this.url.materialPriceApprovalDetail.list, params, this.materialPriceApprovalDetailTable)
          }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        console.log("-------------------------",allValues)
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          materialPriceApprovalDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>